package com.silence.springboot.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

/**
 * Jwt工具类
 */
@Slf4j
public class JwtUtil {

    /**
     * token过期时间
     */
    private static final long TOKEN_EXPIRATION = 1000 * 60 * 60 * 24 * 7;

    /**
     * token签名秘钥
     */
    private static final String TOKEN_SIGN_KEY = "forkFKLJISJFKLFKWJFQFIQWIOFJQOFFQGGSDGFFJIQOEUFIEJFIOQWEFHFQOK5FKOIQWUFFEFE423FIQEOFJHUEWHFKASKDLQWJIFSJDJKFHJIJWO";

    /**
     * 创建token
     *
     * @param currentTime 当前时间
     * @param userId      用户id
     * @return token
     */
    public static String createToken(Long currentTime, Long userId) {
        return Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(currentTime + TOKEN_EXPIRATION))
                .claim("userId", userId)
                .signWith(Keys.hmacShaKeyFor(Decoders.BASE64.decode(TOKEN_SIGN_KEY)), SignatureAlgorithm.HS512)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    /**
     * 解析token
     *
     * @param token token
     * @return Claims
     */
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isBlank(token)) return null;
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(Keys.hmacShaKeyFor(Decoders.BASE64.decode(TOKEN_SIGN_KEY)))
                    .build()
                    .parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            if (claims.get("userId") instanceof Integer)
                return ((Integer) claims.get("userId")).longValue();
            return (Long) claims.get("userId");
        } catch (Exception e) {
            log.warn("解析 userId 失败：", e);
            return null;
        }
    }

}
